/* eslint react/no-string-refs:0 */
import React, {Component} from 'react';
import {Input, Button, Checkbox, Grid, Dialog, Form} from '@alifd/next';
import { message } from "antd";
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faMobileAlt, faPassport, faCode} from '@fortawesome/free-solid-svg-icons';
import CountDownbutton from './CountDownbutton';
import axios from 'axios';
import { connect } from 'react-redux';
import './Login.scss';
import styles from './index.module.scss';

// axios.defaults.headers = {
//     'Content-Type': 'application/json',
//     'User-Agent': 'PostmanRuntime/7.15.2',
//     'Accept': '*/*',
//     'Cache-Control': 'no-cache',
//     'Host': 'hellobmb.fun',
//     'Accept-Encoding': 'gzip, deflate',
//     'Connection': 'keep-alive',
// };
const {Row, Col} = Grid;
const Item = Form.Item;
var tmpSession = "";
var cookie = "";
class Index extends Component {
    static displayName = 'Index';

    static propTypes = {};

    static defaultProps = {};

    constructor(props) {
        super(props);
        this.state = {
            value: {
                account: '',
                phoneNum: '',
                password: '',
                checkbox: false,
            },
            isLoginMode: true,
        };
    }

    formChange = (value) => {
        this.setState({
            value,
        });
    };

    handleChangeLoginMode = () => {
        // message.warning("当前暂未开放注册");
        // return;
        this.setState({
            isLoginMode: !this.state.isLoginMode,
        })
    };

    handleSubmitLogin = (values, errors) => {
        const hide = message.loading('正在登录，请稍后...', 0);
        setTimeout(hide, 1500);
        var _this = this;
        if (errors) {
            console.log('errors', errors);
            return;
        }
        axios.defaults.withCredentials = true;
        axios.get('http://www.techweizhi.com:8080/web/record')
            .then(function (res) {
                axios.post('http://www.techweizhi.com:8080/user/login', {
                        "account": values.account,
                        "password": values.password
                    },
                )
                    .then(function (response) {
                        console.log(response);
                        console.log(res.headers);
                        if(response.data.sessionId != null){
                            tmpSession = response.data.sessionId;
                            console.log(tmpSession);
                            _this.props.onSetJSESSIONID(tmpSession);
                        }
                        if(response.data.data === ""){
                            _this.props.onSetJSESSIONID("");
                            message.error(response.data.msg);
                        }else{
                            message.success(response.data.msg);
                            window.location.href = "./#/unity";
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
                console.log(values);
            })
    };

    handleLoginVisitor() {
        var _this = this;
        const hide = message.loading('正在登录，请稍后...', 0);
        setTimeout(hide, 1500);
        axios.defaults.withCredentials = true;
        axios.get('http://www.techweizhi.com:8080/web/record')
            .then(function (res) {
                axios.post('http://www.techweizhi.com:8080/user/loginVisitor', {
                    },
                )
                    .then(function (response) {
                        console.log(response);
                        console.log(res.headers);
                        if(response.data.sessionId != null){
                            tmpSession = response.data.sessionId;
                            console.log(tmpSession);
                            _this.props.onSetJSESSIONID(tmpSession);
                        }
                        if(response.data.data === ""){
                            _this.props.onSetJSESSIONID("");
                            message.error(response.data.msg);
                        }else{
                            message.success(response.data.msg);
                            window.location.href = "./#/unity";
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            })
    }
    handleSendMsg(values) {
        this.setState({
            flag: false,
        });
        const _this = this;
        console.log(this.state.phoneNum);
        var reg = /^1[3|4|5|7|8][0-9]{9}$/; //验证手机号码规则
        var flag = reg.test(this.state.phoneNum);
        if (flag) {
            console.log("手机号码符合标准");
            message.loading('正在努力提交数据..', 1);
            const _this = this;
            axios.defaults.withCredentials = true;
            axios.post('http://www.techweizhi.com:8080/captcha/getRegisterSMSCode', {
                    "phone": this.state.phoneNum,
                },
            )
                .then(function (response) {
                    console.log(response);
                    var msg = response.data.msg;
                    var state = response.data.state;
                    cookie = response.data.sessionId;
                    if (state === 200) {
                        message.success(msg);
                        _this.setState({
                            flag: true,
                        });
                    } else if (msg !== "") {
                        message.error(msg);
                    } else {
                        message.error("接口请求出现未知错误...");
                    }
                });
        } else {
            message.error('请输入正确的手机号码格式！');
            _this.setState({
                flag: false,
            })
        }
    }
    onPhoneChange(values) {
        this.setState({
            phoneNum: values,
        })
    }
    handleSubmitRegist = (values, errors) => {
        if (errors) {
            console.log('errors', errors);
            return;
        }
        console.log('values:', values);
        message.success('暂未开放');
        // 登录成功后做对应的逻辑处理
        const _this = this;
        axios.defaults.withCredentials = true;
        message.loading('正在努力提交数据..', 1);
        document.cookie = 'JSESSIONID=' + cookie;
        axios.post('http://www.techweizhi.com:8080/user/register',
            {
                "account": this.state.phoneNum,
                "password": values.password,
                "code": values.code
            },
        )
            .then(function (response) {
                var msg = response.data.msg;
                var state = response.data.state;
                if (state === 200) {
                    message.success(msg);
                    _this.setState({
                        flag: true,
                    });
                    window.location.href='/';
                } else if (msg !== "") {
                    message.error(msg);
                } else {
                    message.error("接口请求出现未知错误...");
                }
            });
    };

    render() {
        return (
            <div className={`${styles.container} user-login`}>
                <div className={styles.formContainer}>
                    {/* <h4 className={styles.formTitle}>{this.state.isLoginMode === true ? "天津未知智能科技" : "天津未知智能科技"}</h4> */}
                    <Form
                        value={this.state.value}
                        onChange={this.formChange}
                        size="large"
                        ref="form"
                    >
                        <Item required requiredMessage="必填">
                            <Input
                                innerBefore={<FontAwesomeIcon icon={faMobileAlt} style={{margin: 10}}
                                                              onClick={this.onClick}/>}
                                name="account"
                                size="large"
                                maxLength={20}
                                placeholder="手机号"
                                onChange={this.onPhoneChange.bind(this)}
                            />
                        </Item>
                        {this.state.isLoginMode === true ? null :
                            <Item required requiredMessage="必填" className={styles.checkCode}>
                                <Input
                                    innerBefore={<FontAwesomeIcon icon={faCode} style={{margin: 10}}
                                                                  onClick={this.onClick}/>}
                                    name="code"
                                    size="large"
                                    placeholder="验证码"
                                />
                                <div className={styles.checkCodeButton}
                                     onClick={this.handleSendMsg.bind(this)}
                                >
                                    <CountDownbutton/>
                                </div>
                            </Item>

                        }
                        <Item required requiredMessage="必填">
                            <Input
                                innerBefore={<FontAwesomeIcon icon={faPassport} style={{margin: 10}}
                                                              onClick={this.onClick}/>}
                                name="password"
                                size="large"
                                htmlType="password"
                                placeholder="密码"
                            />
                        </Item>
                        {
                            this.state.isLoginMode
                                ?
                                <Row className={styles.formItem}>
                                    <Form.Submit
                                        type="primary"
                                        onClick={this.handleSubmitLogin}
                                        className={styles.submitBtn}
                                        validate
                                    >
                                        登 录
                                    </Form.Submit>
                                </Row>
                                :
                                <Row className={styles.formItem}>
                                    <Form.Submit
                                        type="primary"
                                        onClick={this.handleSubmitRegist}
                                        className={styles.submitBtn}
                                        validate
                                    >
                                        注 册
                                    </Form.Submit>
                                </Row>
                        }

                        {this.state.isLoginMode
                            ?
                            <Row className={`${styles.tips} tips`}>
                                <a className={styles.link} onClick={this.handleChangeLoginMode.bind(this)}>
                                    立即注册
                                </a>
                            </Row>

                            :
                            <Row className={`${styles.tips} tips`}>
                                <a className={styles.link} onClick={this.handleChangeLoginMode.bind(this)}>
                                    已有账号，马上登录
                                </a>
                            </Row>
                        }
                        <Row className={`${styles.tips} tips`}>
                            <div className={styles.guest} onClick={this.handleLoginVisitor.bind(this)}>游客登录</div>
                        </Row>
                    </Form>
                </div>
            </div>
        );
    }
}
const mapStateToProps = (state) => {
    return {
        JSESSIONID: state.api.JSESSIONID
    };
};
const mapDispatchToProps = (dispatch) => {
    return {
        onSetJSESSIONID(par1) {
            console.log('即将设置sessionID...', par1);
            const action = {
                JSESSIONID: par1,
                type: "setJSESSIONID",
            };
            dispatch(action);
        }
    };
};
export default connect(mapStateToProps, mapDispatchToProps)(Index);
